package com.imooc.mybatisplusappdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.imooc.mybatisplusappdemo.entity.Resource;
import com.imooc.mybatisplusappdemo.dao.ResourceMapper;
import com.imooc.mybatisplusappdemo.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.mybatisplusappdemo.vo.ResourceVO;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author sanchongmen
 * @since 2021-03-22
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

  @Override
  public List<ResourceVO> listResourceByRoleId(long roleId) {
    QueryWrapper<Resource> query = Wrappers.query();
    //获取顶级资源
    query.eq("rr.role_id", roleId).isNull("re.parent_id");
    List<ResourceVO> resourceVOS = baseMapper.listResource(query);

    //根据顶级资源获取子资源
    resourceVOS.forEach(r -> {
      long resourceId = r.getResourceId();
      QueryWrapper<Resource> subQuery = Wrappers.<Resource>query();
      subQuery.eq("rr.role_id", roleId).eq("re.parent_id", resourceId);
      List<ResourceVO> subResourceVOS = baseMapper.listResource(subQuery);

      if (CollectionUtils.isNotEmpty(subResourceVOS)) {
        r.setSubs(subResourceVOS);
      }

    });

    return resourceVOS;
  }
}
